package com.interview.client.sdk;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.interview.client.http.HTTPUtils;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author 11148
 */
public class ClientService {

    //服务器地址配置
    private final static String URL = "http://localhost:80/api/file/";
    //默认本地文件下载地址
    private final static String DOWNLOAD_LOCATION = "D:\\download\\";
    private final static Logger logger = LoggerFactory.getLogger(ClientService.class);

    public static String uploadFile(String filePath){
        String result;
        try{
            File file = new File(filePath);
            if(!file.exists()){
                throw new FileNotFoundException();
            }
            result = HTTPUtils.doPostAndSendFiles(URL + "upload",file);
            return result;
        } catch (FileNotFoundException e){
            logger.error("文件上传失败：找不到文件", e);
            return "文件上传失败：找不到文件";
        }catch (IOException e) {
            logger.error("文件上传失败：IO错误", e);
            return "文件上传失败：找不到文件";
        }
    }

    public static String downloadFile(String uuid){
        String result = "";
        try {
            result = getMetaData(uuid);
            JSONObject jsonObject = JSON.parseObject(result);
            result = jsonObject.getObject("fileType", String.class);
            result = HTTPUtils.doGetAndDownloadFile(URL + "download/" + uuid, DOWNLOAD_LOCATION+uuid+(result == null||"".equals(result)?"":"."+result));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getMetaData(String uuid){
        String result = "";
        try {
            result = HTTPUtils.doGet(URL + "meta/" + uuid, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
